package cn.wizzer.app.sys.modules.services.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import cn.wizzer.app.sys.modules.models.SysParam;
import cn.wizzer.app.sys.modules.services.SysParamService;
import cn.wizzer.framework.base.model.enums.BizExceptionEnum;
import cn.wizzer.framework.base.service.BaseServiceImpl;
import cn.wizzer.framework.util.Result;
import com.alibaba.dubbo.config.annotation.Service;
import org.nutz.dao.Dao;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.plugins.wkcache.annotation.CacheDefaults;
import org.nutz.plugins.wkcache.annotation.CacheRemoveAll;
import org.nutz.plugins.wkcache.annotation.CacheResult;

@IocBean(args = {"refer:dao"})
@Service(interfaceClass = SysParamService.class)
@CacheDefaults(cacheName = "sys_param")
public class SysParamServiceImpl extends BaseServiceImpl<SysParam> implements SysParamService {

    private static final Log log = Logs.get();

    public SysParamServiceImpl(Dao dao) {
        super(dao);
    }

    @Inject
    private Ioc ioc;

    @Inject
    private RedisService redisService;

    @Override
    @CacheResult
    public SysParam fetch() {
        try {
            return this.query().get(0);
        } catch (IndexOutOfBoundsException ie) {
            SysParam param = new SysParam();
            this.insert(param);
            return this.query().get(0);
        }
    }

    @Override
    @CacheRemoveAll
    public void edit(SysParam param) {
        this.update(param);
    }

    @Override
    public void sendEmail(String receiver, String title, String content) {
        SysParam sysParam = this.fetch();
        MailAccount account = new MailAccount();
        account.setHost(sysParam.getEmailHost());
        account.setFrom(sysParam.getEmailUser());
        account.setPort(sysParam.getEmailPort());
        account.setPass(sysParam.getEmailPassword());
        account.setAuth(true);
        account.setUser(sysParam.getEmailUser());
        account.setDebug(false);
        try {
            MailUtil.send(account, CollUtil.newArrayList(receiver), title, content, false);
        } catch (Exception e) {
            log.error(e);
            Result.breakWith(BizExceptionEnum.SEND_CODE_FAIL);
        }
    }

}